package assg.funnycells.util;

import java.io.*;

import assg.funnycells.cells.FunnyCell;
import assg.funnycells.server.CellState;

public class RateLimBufferedReader extends BufferedReader {
    String readline;
    int state;
    FunnyCell funnyCell;
    String cellId;
    int x, y, type, energy;

    String infectedClass, newInfectedClass, antibodyClass, newAntibodyClass;

    public RateLimBufferedReader(Reader in, FunnyCell funnyCell) {
	super(in);
    }

    public void initClassNames(String infectedClass, String newInfectedClass, String antibodyClass, String newAntibodyClass) {
	this.infectedClass = infectedClass;
	this.newInfectedClass = newInfectedClass;
	this.antibodyClass = antibodyClass;
	this.newAntibodyClass = newAntibodyClass;
    }

    public String readLine() throws IOException {
	readline = super.readLine();
	if(readline != null && readline.startsWith(assg.funnycells.server.Cell.CHANGESTATE)) {
	    cellId = StringOperations.parseVal(readline);
	    readline = super.readLine(); x = StringOperations.parseInt(StringOperations.parseVal(readline));
	    readline = super.readLine(); y = StringOperations.parseInt(StringOperations.parseVal(readline));	    
	    readline = super.readLine(); type = StringOperations.parseInt(StringOperations.parseVal(readline));
	    readline = super.readLine(); energy = StringOperations.parseInt(StringOperations.parseVal(readline));
	    readline = super.readLine();

	    Logger.getDefaultLogger().infooverride(cellId + "(" + x + ", " + y + ") CHANGESTATE to " + type + " with energy " + energy);

	    switch(state) {
	    case assg.funnycells.server.CellState.SUSCEPTIBLE:
		try { close(); } catch(Exception e) { }
		(new FunnyCell(x, y, CellState.newType(type), energy, cellId,
			       infectedClass, newInfectedClass, antibodyClass, newAntibodyClass)).start();
		break;
	    case assg.funnycells.server.CellState.INFECTED:
		try { close(); } catch(Exception e) { }
		(new FunnyCell(x, y, CellState.newType(type), energy, cellId,
			       infectedClass, newInfectedClass, antibodyClass, newAntibodyClass)).start();
		break;
	    case assg.funnycells.server.CellState.ANTIBODY:
		try { close(); } catch(Exception e) { }
		(new FunnyCell(x, y, CellState.newType(type), energy, cellId,
			       infectedClass, newInfectedClass, antibodyClass, newAntibodyClass)).start();
		break;
	    }
	    return null;
	} 
	else if(readline != null && readline.startsWith(assg.funnycells.server.Cell.EXIT)) {
	    cellId = StringOperations.parseVal(readline);
	    super.readLine();
	    
	    Logger.getDefaultLogger().infooverride(cellId + " exiting upon signal from server");

	    funnyCell.exit();
	}
	return readline;
    }

}